<?php
class Default_Model_DbTable_RecipeHasIngredients extends Default_Model_DbTable_DbTableEntityAbstract
{
	protected $_db;
	protected $_primary = 'recipe_id';
	
    public function init()
    {
    	$this->_db = Zend_Db_Table::getDefaultAdapter();
    	$this->_name = 'recipe_has_ingredients';
    }
    
    public function addRecipeIngredients($data)
    {
    	if( $this->insert($data) ){
    		return true;
    	}
    }
    
    public function getIngredientsByRecipeId($recipeId)
    {
    	$select = $this->_db->select()
    				   ->from(array('rhi' => 'recipe_has_ingredients'))
    				   ->join(
    				       array('i' => 'ingredients'),
    				       'i.ingredient_id = rhi.ingredient_id'
    				   )
    	               ->where("recipe_id = ?", $recipeId);
    	$result = $this->_db->fetchAll($select);
    	return $result;
    }
    
    public function deleteIngredients($id)
    {
    	$where = $this->getAdapter()->quoteInto('recipe_id = ?', $id);
		$this->delete($where);
    }
    
    public function getMainIngredients()
    {
    	$select = $this->_db->select()
    				   ->from(
    				   		array('rhi' => 'recipe_has_ingredients'),
    				   		array('count' => 'COUNT(rhi.ingredient_id)')
    				   	)
    				   ->join(
    				       array('i' => 'ingredients'),
    				       'i.ingredient_id = rhi.ingredient_id',
    				       array('i.ingredient_id', 'i.ingredient_name')
    				   )
    	               ->where("rhi.is_main = 1")
    	               ->group('rhi.ingredient_id');
    	$result = $this->_db->fetchAll($select);
    	return $result;
    }
}